//
//  Commtools.m
//  PudiEdu
//
//  Created by cong on 15/2/23.
//  Copyright (c) 2015 cong. All rights reserved.
//

#import "ConstansCode.h"
#import "Commtools.h"
//#import "JGProgressHUD.h"
//#import "JGProgressHUDPieIndicatorView.h"
//#import "JGProgressHUDSuccessIndicatorView.h"
//#import "JGProgressHUDIndeterminateIndicatorView.h"
#import <CommonCrypto/CommonDigest.h>
@implementation Commtools

//SYNTHESIZE_SINGLETON_FOR_CLASS(Commtools)

//+(JGProgressHUD *)getShareHud{
//    static JGProgressHUD *sharedInstance = nil;
//
//    @synchronized(self) {
//        if (!sharedInstance) {
//            sharedInstance =  [[JGProgressHUD alloc] initWithStyle:JGProgressHUDStyleDark];
//        }
//    }
//    return sharedInstance;
//}
//
///**
//* 显示类型安卓的文本
//* */
//+(void)showShortToast:(UIView *)view andString:(NSString *)msg{
//
//    JGProgressHUD *HUD = [[JGProgressHUD alloc] initWithStyle:JGProgressHUDStyleDark];
//    HUD.indicatorView = nil;
//    HUD.userInteractionEnabled = YES;
//    HUD.textLabel.text = msg;
//    HUD.delegate = self;
//    HUD.position = JGProgressHUDPositionBottomCenter;
//    HUD.marginInsets = (UIEdgeInsets) {
//            .top = 0.0f,
//            .bottom = 5.0f,
//            .left = 0.0f,
//            .right = 0.0f,
//    };
//
//    [HUD showInView:view];
//
//    [HUD dismissAfterDelay:2.0f];
//}
/**
* 简单的加载等待视图
* */
//+ (void)showProgress:(UIView *)view {
//    JGProgressHUD *HUD = [Commtools getShareHud];
////    HUD.indicatorView =  [[JGProgressHUDIndeterminateIndicatorView alloc] initWithHUDStyle:JGProgressHUDStyleDark];;
////           HUD.textLabel.text = nil;
//
//    [HUD showInView:view];
////    [HUD dismissAfterDelay:1.0f];
//
//}
///**
//* 会自动关闭的加载视图
//* */
//+(void)showProgressCancle:(UIView *)view{
//    NSLog(@"打开HUD");
//    JGProgressHUD *HUD = [Commtools getShareHud];
//    [HUD showInView:view];
//    [HUD dismissAfterDelay:8.0f];
//}
///**
//* 关闭加载视图
//* */
//+(void)dismissProgress{
////    NSLog(@"关闭HUD");
//    [[Commtools getShareHud] dismiss];
//
//}
///**
//* 加载视图，指定位置和文本
//* */
//+(void)showProgress:(UIView *)view andString:(NSString *)msg{
//    JGProgressHUD *HUD = [Commtools getShareHud];
//    HUD.indicatorView = nil;
//    HUD.userInteractionEnabled = YES;
//    HUD.textLabel.text = msg;
//    HUD.delegate = self;
//    HUD.position = JGProgressHUDPositionBottomCenter;
//    [HUD showInView:view];
//
//}
//
///**
//* 上传图片时候的圆型百分比视图
//* */
//+(JGProgressHUD *)showPie2HUD:(UIView *)view{
//    JGProgressHUD *HUD =    [[JGProgressHUD alloc] initWithStyle:JGProgressHUDStyleDark];
//
//    HUD.indicatorView = [[JGProgressHUDPieIndicatorView alloc] initWithHUDStyle:HUD.style];
//
//    HUD.detailTextLabel.text = @"0% Complete";
//
//    HUD.textLabel.text = @"Loading...";
//    [HUD showInView:view];
//
//    return HUD;
//}
//
//
//+(void)showPieHUD:(UIView *)view  {
//    JGProgressHUD *HUD =   [Commtools getShareHud];
//
//    HUD.indicatorView = [[JGProgressHUDPieIndicatorView alloc] initWithHUDStyle:HUD.style];
//
//    HUD.detailTextLabel.text = @"0% Complete";
//
//    HUD.textLabel.text = @"Loading...";
//    [HUD showInView:view];
//
////    HUD.layoutChangeAnimationDuration = 0.0;
//
////    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////        [self incrementHUD:HUD progress:0];
////
////
////    });
//}
//
//+ (void)incrementHUD:(JGProgressHUD *)HUD progress:(int)progress {
////    progress += 1;
//
//    [HUD setProgress:progress/100.0f animated:NO];
//    HUD.detailTextLabel.text = [NSString stringWithFormat:@"%i%% Complete", progress];
////    NSLog(@"progress:%d",progress);
//    if (progress == 100) {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            HUD.textLabel.text = @"成功~!";
//            HUD.detailTextLabel.text = nil;
//
//            HUD.layoutChangeAnimationDuration = 0.3;
//            HUD.indicatorView = [[JGProgressHUDSuccessIndicatorView alloc] init];
//
//
//        });
//
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//
//            [HUD dismiss];
//
//        });
//    }
////    else {
////        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////            [self incrementHUD:HUD progress:progress];
////        });
////    }
//}


+ (NSString *)getCurrentData {


    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *date =  [formatter stringFromDate:[NSDate date]];


    return date;
}

+ (NSString *)getCurrentDataUpdateImg {


    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *date =  [formatter stringFromDate:[NSDate date]];
    return date;
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
    ];
}


#pragma mark--计算高度新方法
+ (CGFloat)labelAutoCalculateRectWith:(NSString*)text FontSize:(CGFloat)fontSize MaxSize:(CGSize)maxSize

{
    
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    
    paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
    
    //  NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:2];
    
    NSDictionary* attributes =@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],
                                NSParagraphStyleAttributeName:paragraphStyle.copy,
                                };
    
    CGSize labelSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    

    
    
    return labelSize.height;
    
}

+ (void)setExtraCellLineHidden: (UITableView *)tableView

{
    
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
   
    
}


+ (void)showMessage:(NSString *)message
{
    NSLog(@"%s",__FUNCTION__);
    
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor whiteColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    //    showview.layer.cornerRadius = 5.0f;
    showview.layer.borderColor = [UIColor yellowColor].CGColor;
    showview.layer.borderWidth = 1;
    //    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 20, kUI_SCREEN_WIDTH, 44);
    label.text = message;
    label.textColor = [UIColor redColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.lineBreakMode = NSLineBreakByCharWrapping;
    label.numberOfLines = 0;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake(0, -64, kUI_SCREEN_WIDTH, 64);
    [UIView animateWithDuration:0.3 animations:^{
        //        showview.alpha = 0;
        showview.frame = CGRectMake(0, 0, kUI_SCREEN_WIDTH, 64);
    } completion:^(BOOL finished) {
        //        showview.frame = CGRectMake(0, -64, SCREENWIDTH, 64);
        //        [showview removeFromSuperview];
    }];
    
    dispatch_main_after(2.0f, ^{
        [UIView animateWithDuration:0.5 animations:^{
            //        showview.alpha = 0;
            showview.frame = CGRectMake(0, -64, kUI_SCREEN_WIDTH, 64);
        } completion:^(BOOL finished) {
            [showview removeFromSuperview];
        }];
    });
}

static void dispatch_main_after(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        block();
    });
}


+ (UIImage *) createImageWithColor: (UIColor *) color
{
    CGRect rect = CGRectMake(0.0f,0.0f,1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *myImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return myImage;
}


+(UINavigationController *)getSelectedNavi:(UIViewController *)vc byRect:(CGRect)frame{
    
    UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:vc];
 
   
    navi.navigationBar.layer.shadowColor = [UIColor grayColor].CGColor; //shadowColor阴影颜色
    navi.navigationBar.layer.shadowOffset = CGSizeMake(1.0f , 1.0f); //shadowOffset阴影偏移x，y向(上/下)偏移(-/+)2
    navi.navigationBar.layer.shadowOpacity = 1.f;
    navi.navigationBar.layer.shadowRadius = 1.0f;//阴影半径
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
//    NSDictionary * dict = [NSDictionary dictionaryWithObject:MAIN_COLOR forKey:NSForegroundColorAttributeName];
//    //大功告成
//    navi.navigationBar.titleTextAttributes = dict;
    navi.view.frame = frame;
    
    return navi;
    
}


+(UIViewController *)getSelected :(UIViewController *)vc byRect:(CGRect)frame{
    
//    UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:vc];
//    
//    [navi.navigationBar setTranslucent:NO];
    vc.view.layer.shadowColor = [UIColor grayColor].CGColor; //shadowColor阴影颜色
    vc.view.layer.shadowOffset = CGSizeMake(1.0f , 1.0f); //shadowOffset阴影偏移x，y向(上/下)偏移(-/+)2
    vc.view.layer.shadowOpacity = 1.f;
    vc.view.layer.shadowRadius = 1.0f;//阴影半径
    
    vc.view.layer.cornerRadius=kCornerRadius;
    vc.view.clipsToBounds=YES;
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    //    NSDictionary * dict = [NSDictionary dictionaryWithObject:MAIN_COLOR forKey:NSForegroundColorAttributeName];
    //    //大功告成
    //    navi.navigationBar.titleTextAttributes = dict;
    vc.view.frame = frame;
    
    return vc;
    
}



+ (UITableViewCell *)tableViewCell:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UITableViewCell class]]) {
            return (UITableViewCell *)nextResponder;
        }
    }
    return nil;
}

+ (UITableView *)tableView:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UITableView class]]) {
            return (UITableView *)nextResponder;
        }
    }
    return nil;
}

+ (Commtools *)sharedCommtools
{
    static Commtools *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
}


-(id)init
{
    self = [super init];
    if (self)
    {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center  addObserver:self selector:@selector(keyboardDidShow)  name:UIKeyboardDidShowNotification  object:nil];
        [center addObserver:self selector:@selector(keyboardDidHide)  name:UIKeyboardWillHideNotification object:nil];
        _keyboardIsVisible = NO;
    }
    return self;
}

- (void)keyboardDidShow
{
    _keyboardIsVisible = YES;
}

- (void)keyboardDidHide
{
    _keyboardIsVisible = NO;
}

- (BOOL)keyboardIsVisible
{
    return _keyboardIsVisible;
}


+ (NSString *) decimalwithFormat:(NSString *)format  floatV:(float)floatV
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    
    [numberFormatter setPositiveFormat:format];
    
    return  [numberFormatter stringFromNumber:[NSNumber numberWithFloat:floatV]];
}

#pragma mark -------间距字体

+(NSAttributedString * )attributedStringFromString:(NSString * )string;
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 6;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:kFont(17),
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    return [[NSAttributedString alloc] initWithString:string attributes:attributes];
}

#pragma mark -------间距字体高度
+ (CGSize)getStringaString:(NSString*)aString andWidth:(CGFloat  )width

{

    
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 8;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:kFont(16),
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    NSAttributedString* atrString = [[NSAttributedString alloc] initWithString:aString attributes:attributes];
    
    
    CGSize size;
    
    

    
    
    
    NSRange range = NSMakeRange(0, atrString.length);
    
    
    
    NSDictionary* dic = [atrString attributesAtIndex:0 effectiveRange:&range];
    
    

    
    size=[aString boundingRectWithSize:CGSizeMake(width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    


    return  size;
    
    
    
}

#pragma mark--- 判断是否是零时账号－－－正则
+(BOOL)isKongGe:(NSString *)string
{
    
    //
    //    NSInteger portInteger = [[self.currentLoginName s:@"孩教圈[\\d]*]" capture:1L] integerValue];
    
    
    NSError *error = NULL;
    NSString *patternIFrame;
    NSRegularExpression *regex;
    //    int offset = 0;
    //parse <iframe>
    patternIFrame = @"\\s+";
    // 配置regex对象
    regex = [NSRegularExpression regularExpressionWithPattern:patternIFrame options:NSRegularExpressionCaseInsensitive error:&error];
    // 这里是用来从字符串中查询符合规则的字符串，然后返回结果
    NSArray *matchResult = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
    
    
    
    
    
    
    
    
    
    
    
    if (matchResult&&matchResult.count>0) {
        
        NSLog(@"是空格-------%@",string);
        
        [SVProgressHUD showImage:nil status:@"不能发送纯空格"];
        
        
        return YES;
        
    }else
    {
        NSLog(@"不是空格-------%@",string);
        
        return NO;
        
    }
    
}






+(UIImage *)rotateImage:(UIImage *)aImage

{
    CGImageRef imgRef = aImage.CGImage;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    CGFloat scaleRatio = 1;
    CGFloat boundHeight;
    UIImageOrientation orient = 3;
    
    switch(orient)
    {
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
        case UIImageOrientationDown: //EXIF = 3
//            transform = CGAffineTransformMakeTranslation(width, height);
            transform = CGAffineTransformRotate(transform, M_PI*2);
            break;
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(height, width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
    }
    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    CGContextConcatCTM(context, transform);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}


+(BOOL)isDaytime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH"];
    NSString *str = [formatter stringFromDate:[NSDate date]];
    int time = [str intValue];
    if (time>=18||time<=06) {
        return NO;
    }
    else{
        return YES;
    }
}

+(NSString *)toJsonStringFrom:(id)theData
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    if ([jsonData length] >0 && error == nil){
        NSString *jsonString = [[NSString alloc] initWithData:jsonData
           
                                                     encoding:NSUTF8StringEncoding];
        
        return jsonString;
        
    }else{
        return nil;
    }
}


//+ (void)setExtraCellLineHidden: (UITableView *)tableView{
//    
//    UIView *view =[ [UIView alloc]init];
//    
//    view.backgroundColor = [UIColor clearColor];
//    
//    [tableView setTableFooterView:view];
//    
//    [tableView setTableHeaderView:view];
//
//    
//}
@end
